package com.itlong.cloud.rabbitmq.consumer.entranceconsumers;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.itlong.cloud.POJO.PO.DeviceBusinessEntranceChangeLogPO;
import com.itlong.cloud.POJO.PO.TimeTaskDeadMessageQueuePO;
import com.itlong.cloud.commons.service.ICloudEntranceService;
import com.itlong.cloud.commons.service.IPushCloudEntranceChangeLogService;
import com.itlong.cloud.constants.RabbitMQConstant;
import com.itlong.cloud.enumerate.CloudEntranceChangeBusinessEnum;
import com.itlong.cloud.utils.node.JsonUtil;
import com.rabbitmq.client.Channel;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <desc>
 *     云门禁同步业务指令消费过程同步业务指令操作队列消费者
 * </desc>
 *
 * @createDate 2019/02/27
 */
@Component
public class CloudEntranceChangeBusinessConsumer04 {

    private static final Logger LOG = LoggerFactory.getLogger(CloudEntranceChangeBusinessConsumer04.class);

    @Autowired
    private ICloudEntranceService iCloudEntranceService;

    @Autowired
    private IPushCloudEntranceChangeLogService iPushCloudEntranceChangeLogService;

    /**
     * <desc>
     *      云门禁同步业务指令消费过程
     * </desc>
     *
     * @param message 监听到的业务消息
     * @param channel 频道
     * @author wangzhi
     * @createDate 2019/02/27
     */
    @RabbitListener(queues = RabbitMQConstant.RABBITMQ_HANDLE_CLOUD_ENTRANCE_CHANGE_BUSINESS_QUEUE)
    public void process(Message message, Channel channel) throws IOException {
        byte[] body = message.getBody();
        try {
            Thread.sleep(700);
            TimeTaskDeadMessageQueuePO timeTaskDeadMessageQueuePO = JsonUtil.toObject(new String(body),
                    TimeTaskDeadMessageQueuePO.class);
            String content = timeTaskDeadMessageQueuePO.getMessageContent();
            JSONObject jsData = JSONObject.parseObject(content);

            JSONArray jsDataArr = jsData.getJSONArray("data");
            List<DeviceBusinessEntranceChangeLogPO> changeLogPOS = JSON.parseObject(JSONObject.toJSONString(jsDataArr), new TypeReference<List<DeviceBusinessEntranceChangeLogPO>>() {});
            if (changeLogPOS != null && changeLogPOS.size()>0){
                List<DeviceBusinessEntranceChangeLogPO> removeChangeLogPOS = new ArrayList<>();
                for (DeviceBusinessEntranceChangeLogPO po : changeLogPOS) {
                    if (StringUtils.isBlank(po.getProjectId())) {
                        removeChangeLogPOS.add(po);
                    } else {
                        JSONArray commandDataArr = null, commandAttacheDataArr;
                        JSONObject dataJs;
                        String buildAndUnitId;
                        if (CloudEntranceChangeBusinessEnum.PUSH_ROOM_PWD.getCommandType().equals(po.getCommandType())) {  //固定密码信息变化
                            LOG.info("云门禁固定密码信息指令处理消费者数据：" + po.getCommandParameter());
                            commandDataArr = JSONArray.parseArray(po.getCommandParameter());
                            LOG.info("云门禁固定密码信息指令处理parseArray得到数据：" + commandDataArr);
                        }
                        if (commandDataArr != null && commandDataArr.size() > 0) {
                            commandAttacheDataArr = new JSONArray();
                            for (int i = 0; i < commandDataArr.size(); i++) {
                                dataJs = commandDataArr.getJSONObject(i);
                                buildAndUnitId = iCloudEntranceService.deviceChangeLogGetBuildAndUnitIdByRoomId(dataJs.getString("roomId"));
                                dataJs.put("buildId", buildAndUnitId.substring(0, buildAndUnitId.indexOf(",")));
                                dataJs.put("unitId", buildAndUnitId.substring(buildAndUnitId.indexOf(",") + 1, buildAndUnitId.length()));
                                commandAttacheDataArr.add(dataJs);
                            }
                            po.setCommandParameter(JSONObject.toJSONString(commandAttacheDataArr));
                        }
                    }
                }
                if (removeChangeLogPOS.size() > 0) {
                    LOG.info("RabbitMQ_云门禁同步业务指令操作队列_异常生产数据:\n" + JSONObject.toJSONString(removeChangeLogPOS));
                    changeLogPOS.removeAll(removeChangeLogPOS);
                }
                if (changeLogPOS.size() > 0) {
                    if (changeLogPOS.get(0).getCommandType() == 1) {//项目信息变更
                        iPushCloudEntranceChangeLogService.setPushProject(changeLogPOS);
                    }
                    if (changeLogPOS.get(0).getCommandType() == 2) {//固定密码信息
                        iPushCloudEntranceChangeLogService.setPushFixedPassword(changeLogPOS);
                    }
                    if (changeLogPOS.get(0).getCommandType() == 3) {//云门禁业务服务器地址变更
                        iPushCloudEntranceChangeLogService.updateFull(changeLogPOS.get(0).getProjectId(),changeLogPOS.get(0).getCommandParameter());
                    }
                    if (changeLogPOS.get(0).getCommandType() == 4) {//云门禁单个设备物理地址变更
                        iPushCloudEntranceChangeLogService.setPushDeviceOne(changeLogPOS);
                    }
                    if (changeLogPOS.get(0).getCommandType() == 5) {//设备信息变更
                        iPushCloudEntranceChangeLogService.setPushDevice(changeLogPOS);
                    }
                    if (changeLogPOS.get(0).getCommandType() == 6) {//用户所在项目信息变更
                        iPushCloudEntranceChangeLogService.setPushUserProject(changeLogPOS, 1);
                    }
                    if (changeLogPOS.get(0).getCommandType() == 7) {//用户的房间信息变更
                        iPushCloudEntranceChangeLogService.setPushUserProject(changeLogPOS, 2);
                    }
                    if (changeLogPOS.get(0).getCommandType() == 9) {//黑名单信息变更
                        iPushCloudEntranceChangeLogService.setBlackList(changeLogPOS);
                    }
                    if(changeLogPOS.get(0).getCommandType() == 8){//用户临时权限变更
                        iPushCloudEntranceChangeLogService.setPushTempAuth(changeLogPOS);
                    }
                    if(changeLogPOS.get(0).getCommandType() == 10){//多媒体信息变更
                        iPushCloudEntranceChangeLogService.setPushMedia(changeLogPOS);
                    }
                    if(changeLogPOS.get(0).getCommandType() == 11){//人脸信息变更
                        iPushCloudEntranceChangeLogService.setPushFaceInfo(changeLogPOS);
                    }
                }
            }
            //LOG.info("RabbitMQ_云门禁同步业务指令操作队列消费端:"+ content);
        } catch (Exception ex) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
            LOG.error("【RabbitMQ_云门禁同步业务指令消费端】:消费异常", ex);
        }
        finally {
            //手动确认消息消费成功。
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }

}
